package edu.zcmu.seckill.utils;

import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;

import java.util.Random;

public class Md5Utils {
    /**
     * 加盐参数
     */
    private static final String SALT = "";

    /**
     * 加密算法
     */
    private static final String ALGORITHM_NAME = "md5";

    /**
     * hash运算次数
     */
    private static final int HASH_ITERATIONS = 5;

    /**
     * 数据加密
     * @param passWord 需要加密的字符
     * @return 返回的结果
     */
    public static String encrypt(String passWord) {
        return new SimpleHash(ALGORITHM_NAME, passWord, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
    }

    /**
     * 密码校验
     * @param passWord 用户输入的密码
     * @param passwordMy 数据库中的免密
     * @return 结果
     */
    public static Boolean checkEncrypt(String passWord, String passwordMy) {
        String newPassWord = new SimpleHash(ALGORITHM_NAME, passWord, ByteSource.Util.bytes(SALT), HASH_ITERATIONS).toHex();
        return passwordMy.equals(newPassWord);
    }

    /**
     *  获取长度为6的随即盐
     * @return salt字符
     */
    public static String getSalt(){
        char[] chars = ("abcdefghijklmnopqrstuvwsyz1234567890").toCharArray();
        StringBuilder sb = new StringBuilder();
        for(int i = 0; i < 6; i++){
            //Random().nextInt()返回值为[0,n)
            char aChar = chars[new Random().nextInt(chars.length)];
            sb.append(aChar);
        }
        return sb.toString();
    }

}
